"""
订单与订单项模型
"""
from sqlalchemy import Column, BigInteger, String, Text, Integer, DateTime, ForeignKey, DECIMAL, SmallInteger
from sqlalchemy.orm import relationship
from datetime import datetime
from database.base import Base


class Order(Base):
    __tablename__ = "orders"

    id = Column(BigInteger, primary_key=True, index=True, comment="主键ID")
    order_no = Column(String(64), unique=True, index=True, nullable=False, comment="订单号(唯一)")
    user_id = Column(BigInteger, ForeignKey("users.id", ondelete="CASCADE"), index=True, nullable=False, comment="用户ID")
    total_amount = Column(DECIMAL(10, 2), default=0, comment="订单总金额")
    status = Column(SmallInteger, default=0, comment="状态：0-已创建，1-已支付，2-已取消")
    created_at = Column(DateTime, default=datetime.now, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")

    items = relationship("OrderItem", back_populates="order", cascade="all, delete-orphan")


class OrderItem(Base):
    __tablename__ = "order_items"

    id = Column(BigInteger, primary_key=True, index=True, comment="主键ID")
    order_id = Column(BigInteger, ForeignKey("orders.id", ondelete="CASCADE"), index=True, nullable=False, comment="订单ID")
    goods_id = Column(BigInteger, index=True, nullable=False, comment="商品ID")
    name = Column(String(200), nullable=False, comment="商品名称")
    price = Column(DECIMAL(10, 2), nullable=False, comment="单价")
    qty = Column(Integer, nullable=False, default=1, comment="数量")
    image_url = Column(String(500), comment="商品图片")

    order = relationship("Order", back_populates="items")


